<template>
  <el-dialog
    v-loading="isLoading"
    class="dialog"
    :title="isEdit ? '修改学生' : '添加学生'"
    :visible.sync="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleClose"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
    >
      <div class="common">
        <el-form-item labelPosition="left" prop="stuName" label="姓名:">
          <el-input
            style="width: 70%"
            clearable
            placeholder="请输入学生姓名"
            v-model="form.stuName"
          ></el-input>
        </el-form-item>
        <el-form-item labelPosition="left" label="学籍号:">
          <el-input
            clearable
            style="width: 70%"
            placeholder="请输入学生学籍号"
            v-model="form.stuStatusNum"
          ></el-input>
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item labelPosition="left" label="性别:" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item labelPosition="left" label="出生年月:">
          <el-date-picker
            style="width: 70%"
            clearable
            :picker-options="pickerOptions"
            v-model="form.birthTime"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
      </div>
      <div class="common">
        <el-form-item labelPosition="left" label="学号:">
          <el-input
            clearable
            placeholder="请输入学生学号"
            v-model="form.stuNum"
            style="width: 70%"
          ></el-input>
        </el-form-item>
        <el-form-item labelPosition="left" label="民族:">
          <!--         <el-input v-model="form.mz" placeholder="请输入学生民族"></el-input>-->
          <el-select
            style="width: 70%"
            v-model="form.mz"
            placeholder="请选择学生民族"
          >
            <el-option
              v-for="(item, index) in mzOption"
              :label="item.name"
              :value="item.name"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <!--      <div class="common">-->
      <!--        <el-form-item labelPosition="left" prop="phoneNum" label="家长手机号:">-->
      <!--          <i v-for="(item, index) in form.phoneNum" :key="index">-->
      <!--            <el-input-->
      <!--              :disabled="isEdit"-->
      <!--              clearable-->
      <!--              maxLength="11"-->
      <!--              style="width: 70%; margin-bottom: 10px"-->
      <!--              placeholder="请输入家长手机号"-->
      <!--              v-model="item.mobile"-->
      <!--            ></el-input>-->
      <!--            <i-->
      <!--              v-if="!isEdit"-->
      <!--              @click="addPhone"-->
      <!--              class="el-icon-circle-plus-outline"-->
      <!--            ></i>-->
      <!--            <i-->
      <!--              v-if="!isEdit"-->
      <!--              @click="delPhone(index)"-->
      <!--              class="el-icon-delete"-->
      <!--            ></i>-->
      <!--          </i>-->
      <!--        </el-form-item>-->
      <!--      </div>-->
      <div class="common">
        <el-form-item label-position="left" label="学生头像:">
          <el-upload
            class="upload-demo"
            drag
            v-loading="loading"
            :on-success="picUpload"
            :before-upload="beforeUpload"
            :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
            name="file"
            :headers="{
              'access-token': $store.state.user.TOKEN,
            }"
            multiple
          >
            <div v-if="!form.pic">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </div>
            <img
              style="
                width: auto;
                height: auto;
                max-height: 100%;
                max-width: 100%;
              "
              v-if="form.pic"
              :src="$store.state.user.BASE_URL + form.pic"
              alt=""
            />
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose()">取 消</el-button>
      <el-button
        size="small"
        :loading="buttonLoading"
        type="primary"
        @click="submit()"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { studentDeatil, studentAddasEdit } from "@/api/school/student";
import moment from "moment";
import cloneDeep from "lodash/cloneDeep";
import { verifyMobile } from "@/utils/validate";
import encryption from "@/utils/encryption";
import Decrypt from "@/utils/Decrypt";
export default {
  data() {
    let validatePhone = (rule, value, callback) => {
      if (!value.every((item) => item.mobile)) {
        // callback(new Error('长度必须在2-10个之间'))
        callback(new Error("请输入手机号"));
      } else if (!value.every((item) => verifyMobile(item.mobile))) {
        callback(new Error("请输入正确的手机格式"));
      } else {
        callback(); // 通过
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      mzOption: [
        { id: 1, name: "汉族" },
        { id: 2, name: "蒙古族" },
        { id: 3, name: "回族" },
        { id: 4, name: "藏族" },
        { id: 5, name: "维吾尔族" },
        { id: 6, name: "苗族" },
        { id: 7, name: "彝族" },
        { id: 8, name: "壮族" },
        { id: 9, name: "布依族" },
        { id: 10, name: "朝鲜族" },
        { id: 11, name: "满族" },
        { id: 12, name: "侗族" },
        { id: 13, name: "瑶族" },
        { id: 14, name: "白族" },
        { id: 15, name: "土家族" },
        { id: 16, name: "哈尼族" },
        { id: 17, name: "哈萨克族" },
        { id: 18, name: "傣族" },
        { id: 19, name: "黎族" },
        { id: 20, name: "傈僳族" },
        { id: 21, name: "佤族" },
        { id: 22, name: "畲族" },
        { id: 23, name: "高山族" },
        { id: 24, name: "拉祜族" },
        { id: 25, name: "水族" },
        { id: 26, name: "东乡族" },
        { id: 27, name: "纳西族" },
        { id: 28, name: "景颇族" },
        { id: 29, name: "柯尔克孜族" },
        { id: 30, name: "土族" },
        { id: 31, name: "达翰尔族" },
        { id: 32, name: "么佬族" },
        { id: 33, name: "羌族" },
        { id: 34, name: "布朗族" },
        { id: 35, name: "撒拉族" },
        { id: 36, name: "毛南族" },
        { id: 37, name: "仡佬族" },
        { id: 38, name: "锡伯族" },
        { id: 39, name: "阿昌族" },
        { id: 40, name: "普米族" },
        { id: 41, name: "塔吉克族" },
        { id: 42, name: "怒族" },
        { id: 43, name: "乌孜别克族" },
        { id: 44, name: "俄罗斯族" },
        { id: 45, name: "鄂温克族" },
        { id: 46, name: "德昂族" },
        { id: 47, name: "保安族" },
        { id: 48, name: "裕固族" },
        { id: 49, name: "京族" },
        { id: 50, name: "塔塔尔族" },
        { id: 51, name: "独龙族" },
        { id: 52, name: "鄂伦春族" },
        { id: 53, name: "赫哲族" },
        { id: 54, name: "门巴族" },
        { id: 55, name: "珞巴族" },
        { id: 56, name: "基诺族" },
      ],
      isLoading: false,
      loading: false,
      buttonLoading: false,
      form: {
        stuId: "",
        stuNum: "",
        stuStatusNum: "",
        stuName: "",
        sex: null,
        birthTime: "",
        pic: "",
        mz: "",
        phoneNum: [
          {
            id: 0,
            mobile: "",
          },
        ],
      },
      rules: {
        stuName: [
          {
            required: true,
            message: "请输入学生姓名",
          },
          {
            min: 2,
            max: 4,
            message: "长度必须在2-4个之间",
            trigger: "blur",
          },
        ],
        stuNum: [
          {
            required: true,
            message: "请输入学生学号",
          },
        ],
        stuStatusNum: [
          {
            required: true,
            message: "请输入学籍号",
          },
        ],
        mz: [
          {
            required: true,
            message: "请选择民族",
          },
        ],
        sex: [
          {
            required: true,
            message: "请选择学生性别",
          },
        ],
        birthTime: [
          {
            required: true,
            message: "请选择学生生日",
          },
        ],
        pic: [
          {
            required: true,
            message: "请上传学生头像",
          },
        ],
        phoneNum: [
          {
            required: true,
            message: "请上传手机号",
          },
          {
            validator: validatePhone,
            trigger: "blur",
          },
        ],
      },
    };
  },

  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    item: {
      type: Object,
      default: {},
    },
    dialogVisible: {
      type: Boolean,
    },
    classId: {
      type: String,
    },
  },
  watch: {
    isEdit: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.getStudentMessage(this.item.stuId);
        }
      },
    },
  },
  methods: {
    beforeUpload(file) {
      this.loading = true;
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
        this.loading = false;
      }
      return types.includes(fileSuffix);
    },
    validator() {
      this.$refs.form.validate(() => {});
    },
    handleClose(done) {
      this.$emit("close", done);
    },
    picUpload(e) {
      if (e.code === 200) {
        this.form.pic = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.loading = false;
      this.validator();
    },
    getStudentMessage(id) {
      this.isLoading = true;
      studentDeatil(id).then((response) => {
        // this.form = response.result;
        if (response.code === 200) {
          let res = response.result;
          if (res.phoneNum.length) {
            res.phoneNum = res.phoneNum.map((item, index) => ({
              id: index,
              mobile: Decrypt(item),
            }));
          } else {
            res.phoneNum.push({ id: this.form.phoneNum.length, mobile: "" });
          }
          if (res.birthTime) {
            res.birthTime = moment(res.birthTime).format("yyyy-MM-DD");
          } else {
            res.birthTime = "";
          }
          res.classId = this.classId;
          this.form = cloneDeep(res);
        }
        this.isLoading = false;
      });
    },
    submit() {
      this.$refs.form.validate((e) => {
        if (e) {
          this.buttonLoading = true;
          let phoneNum = this.form.phoneNum.map((item) =>
            encryption(item.mobile)
          );
          studentAddasEdit({
            ...this.form,
            classId: this.classId,
            phoneNum,
            schoolId: this.$store.state.user.USER_INFO.pscShId,
            schoolName: this.$store.state.user.USER_INFO.pscShName,
            birthTime: this.form.birthTime ? this.form.birthTime : "",
          }).then((response) => {
            this.buttonLoading = false;
            if (response.code === 200) {
              this.$emit("submit");
              this.$message.success("添加成功！");
            } else {
              this.$message.error(response.message);
            }
          });
        }
      });
    },
    addPhone() {
      this.form.phoneNum.push({ id: this.form.phoneNum.length, mobile: "" });
    },
    delPhone(index) {
      if (this.form.phoneNum.length > 1) {
        this.form.phoneNum.splice(index, 1);
      } else {
        this.$message.error("至少保留一个家长手机号");
      }
      this.validator();
    },
  },
};
</script>
<style lang="scss" scoped>
.common {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .el-form-item {
    flex: 1;
  }
}
::v-deep .el-dialog {
  margin-top: 8vh !important;
}
.el-icon-circle-plus-outline {
  margin-left: 20px;
  &::before {
    font-size: 24px;
    color: #409eff;
  }
}
.el-icon-delete {
  margin-left: 20px;
  &::before {
    font-size: 24px;
    color: #f56c6c;
  }
}
::v-deep .el-upload-list__item {
  display: none;
}
::v-deep .el-upload--text {
  width: 100%;
}
::v-deep .el-upload-dragger {
  width: 70%;
}
::v-deep .el-form {
  padding-left: 60px;
}
</style>
